#include <QtGui>
#include "dragtreeview.h"
#include "attributesmodel.h"
//
DragTreeView::DragTreeView( QWidget *p) 
	: QTreeView(p)
{
    setAcceptDrops(true);
    setDragEnabled(true);
	setDragDropMode(QAbstractItemView::DragDrop);
}
//
void DragTreeView::dragEnterEvent(QDragEnterEvent *event)
{
	if (event->mimeData()->hasFormat("application/x-attribute")){		
       event->setDropAction(Qt::MoveAction);
       event->accept();
	}
	else
	if (event->mimeData()->hasText()) {
        event->acceptProposedAction();
    } else {
       event->ignore();
    }
}
//
void DragTreeView::dragMoveEvent(QDragMoveEvent *event)
{
	if (event->mimeData()->hasFormat("application/x-attribute")){		
            event->setDropAction(Qt::MoveAction);
            event->accept();		
	}
	else
	if (event->mimeData()->hasText()) 
        event->acceptProposedAction();
    else 
	    event->ignore();
}
//
void DragTreeView::dropEvent(QDropEvent *event)
{
	if (event->mimeData()->hasFormat("application/x-attribute")){
		// change attribute number
        const QMimeData *mime = event->mimeData();
        QByteArray itemData = mime->data("application/x-attribute");
        QDataStream dataStream(&itemData, QIODevice::ReadOnly);
        int    nom;
        dataStream >> nom;
		
		QModelIndex  to = indexAt(event->pos());		// where move

		((AttributesModel*)model())->moveAttribute(nom,to);		
		event->accept();		
	}
	else
	if (event->mimeData()->hasText()) {
        QStringList pieces = event->mimeData()->text().split(QRegExp("\\\n+"),QString::SkipEmptyParts);
        // adding words into 
        foreach (QString piece, pieces){
			QMap<QString,QString> params;
			if(piece.simplified().isEmpty()) continue;			
			params["alias"] = piece.simplified();
			params["name"]  = ((AttributesModel*)model())->newName();
			((AttributesModel*)model())->addAttribute(params);
        }
        event->acceptProposedAction();
    } else 
			event->ignore();
}

void DragTreeView::keyPressEvent(QKeyEvent *e)
{
	
	if(e->key()==Qt::Key_Delete){
		//qDebug() << Q_FUNC_INFO << e->key();
		foreach(QModelIndex index,selectedIndexes()){
			qDebug() << "removing";
			model()->removeRow(index.row());
		}
	}
}